package com.jaws.core.common.validator;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Set;

import javax.validation.ConstraintViolation;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import com.jaws.core.mvc.exception.JawsMvcExceptionCode;

/**
 * 通用参数解析
 * 
 * @author maojian
 * @date 2017-05-16 10:45:44
 * @since v1.0.0
 */
public class ValidatorAspect {

	private JawsValidator jawsValidator;

	public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
		// 方法参数校验
		MethodSignature ms = (MethodSignature) pjp.getSignature();
		Method method = ms.getMethod();
		Object target = pjp.getTarget();
		Object[] args = pjp.getArgs();
		Set<ConstraintViolation<Object>> violations = jawsValidator.getValidator().forExecutables().validateParameters(target, method, args);
		if (!violations.isEmpty()) {
			throw JawsMvcExceptionCode.PARAM_ERROR.exp(getViolationMsg(violations));
		}
		Object retVal = pjp.proceed();
		return retVal;
	}

	private String getViolationMsg(Set<ConstraintViolation<Object>> violations) {
		StringBuilder sb = new StringBuilder();
		Iterator<ConstraintViolation<Object>> iter = violations.iterator();
		while (iter.hasNext()) {
			ConstraintViolation<Object> cv = iter.next();
			// String argsName = cv.getPropertyPath().toString();
			// sb.append(argsName);
			sb.append(cv.getMessage());
			if (iter.hasNext()) {
				sb.append(",");
			}
		}
		return sb.toString();
	}

	public JawsValidator getDefaultValidator() {
		return jawsValidator;
	}

	public void setDefaultValidator(JawsValidator defaultValidator) {
		this.jawsValidator = defaultValidator;
	}

}
